package org.robot.scm.platform.server.handler;

import static org.robot.scm.platform.server.LockKey.LOCK_KEY;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.server.common.DefaultRunner;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.server.ExecuteParam;
import org.robot.scm.utils.JsonHelper;

@Slf4j
@NoArgsConstructor
public class ExecuteHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/execute";
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("POST")) {
            sendSuccessResponse(exchange, "请求非法");
            return;
        }

        // 并发校验
        String locker = RedisCacheHelper.get(LOCK_KEY);
        if (StringUtils.isNotBlank(locker)) {
            sendSuccessResponse(exchange, "有任务正在执行中", locker);
            return;
        }

        // 读取请求体
        String requestBody = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
        ExecuteParam executeParam = JsonHelper.toObject(requestBody, ExecuteParam.class);
        if (Objects.isNull(executeParam) || StringUtils.isBlank(executeParam.getFileKey())) {
            sendSuccessResponse(exchange, "先上传脚本再执行");
            return;
        }

        RedisCacheHelper.put(LOCK_KEY, JsonHelper.toJSONString(executeParam));

        // 异步防止阻塞
        CompletableFuture.runAsync(() -> new DefaultRunner().start(config(PlatformEnum.SQL), executeParam));

        sendSuccessResponse(exchange, "执行成功", executeParam.getFileKey());
    }

}
